package com.xudu.controller.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xudu.common.Result;
import com.xudu.controller.IUserController;
import com.xudu.entity.User;
import com.xudu.service.IUserService;
import com.xudu.utils.JWTUtil;
import com.xudu.utils.RedisUtils;
import com.xudu.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xudu
 * @since 2024-04-28
 */
@RestController
public class UserControllerImpl implements IUserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisUtils redisUtils;
//    @Autowired
//    private RedisTemplate redisTemplate;


    @Override
    public Result login(@RequestBody User user)  {


        if (iUserService.login(user)){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(User::getUsername,user.getUsername());
            User dbuser = iUserService.getOne(queryWrapper);

            //生成token
            String sign = JWTUtil.sign(user.getUsername());

            //将token存储在redis中
            redisUtils.setRedisContent(dbuser.getUsername(),sign,200L);
//            redisTemplate.opsForValue().set(sign, dbuser.getUsername());
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(dbuser,userVo);

            //将token赋值给userVo 用于前端返回
            userVo.setToken(sign);

            return Result.success(userVo);

        }else {
            return Result.error("用户名或密码错误");
        }

    }


    @Override
    public Result register(@RequestBody User user) {
        //判断是否为空

        //判断用户名是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername,user.getUsername());
        User dbuser = iUserService.getOne(queryWrapper);
        if(dbuser==null){
            boolean register = iUserService.register(user);
            if (register){
                return Result.success(user);
            }else {
                return Result.error("用户注册失败！");
            }

        }else {
            return Result.error("用户名重复！");
        }

    }

    @Override
    public Result exit(@RequestBody User user) {
        Boolean b = redisUtils.deleteRedisContent(user.getUsername());
        if (b){
            return Result.success();
        }
        return Result.error("退出失败！");
    }

}
